package com.fow.core.platform.push.iosOrigin;

import com.fow.core.util.StopWatch;
import com.fow.core.util.StringUtils;
import javapns.devices.Device;
import javapns.devices.implementations.basic.BasicDevice;
import javapns.notification.AppleNotificationServerBasicImpl;
import javapns.notification.PushNotificationManager;
import javapns.notification.PushNotificationPayload;
import javapns.notification.PushedNotification;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Async;

import java.util.ArrayList;
import java.util.List;


/**
 * Created by suggestion on 2015/5/21.
 */
public class IOSMessagePushService {

    private static Logger logger = LoggerFactory.getLogger(IOSMessagePushService.class);

    private final static int badge = 1;//图标小红圈的数值

    private final static String sound = "default";//铃音

    private String certificatePath;
    private String certificatePassword;

    public IOSMessagePushService() {
    }

    public void setCertificatePath(String certificatePath) {
        this.certificatePath = certificatePath;
    }

    public void setCertificatePassword(String certificatePassword) {
        this.certificatePassword = certificatePassword;
    }

    @Async
    public void run(String deviceToken, String content, String sender, boolean type) {
        if(!StringUtils.hasText(deviceToken))
            return;

        List<String> tokens = new ArrayList<String>();
        tokens.add(deviceToken);

        StopWatch stopWatch = new StopWatch();

        logger.debug("iOS push message begin, elapsed = " + stopWatch.elapsedTime() + "ms");
        try {
            PushNotificationPayload payLoad = new PushNotificationPayload();
            //payLoad.addAlert(content); // 消息内容
            payLoad.addCustomAlertActionLocKey(sender);
            payLoad.addCustomAlertBody(content);
            payLoad.addBadge(badge); // iphone应用图标上小红圈上的数值
            if (StringUtils.hasText(sound)) {
                payLoad.addSound(sound);//铃音
            }

            PushNotificationManager pushManager = new PushNotificationManager();
            //true：表示的是产品发布推送服务 false：表示的是产品测试推送服务
            pushManager.initializeConnection(new AppleNotificationServerBasicImpl(this.getClass().getClassLoader().getResource(certificatePath).getPath(), certificatePassword, type));
            List<PushedNotification> notifications = new ArrayList<PushedNotification>();
            // 发送push消息
            Device device = new BasicDevice();
            device.setToken(tokens.get(0));
            PushedNotification notification = pushManager.sendNotification(device, payLoad, true);
            notifications.add(notification);
            pushManager.stopConnection();

        }
        catch (Exception e)
        {
            logger.error(e.getMessage(),e);
        }
        finally {
            logger.debug("iOS push finished, elapsed = " + stopWatch.elapsedTime() + "ms");
        }
    }
}
